package logic

import (
	"context"
	"fmt"
	"math/rand"
	"shop-hub/cache"
	"shop-hub/models"
	"shop-hub/pkg"
	"shop-hub/shoprpc/internal/svc"
	"shop-hub/shoprpc/shoprpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 登录
func (l *LoginLogic) Login(in *shoprpc.LoginRequest) (*shoprpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Account).Result()
	if result != in.SendSms {
		return nil, fmt.Errorf("短信验证码错误,登录失败")
	}

	result1, _ := cache.Rdb.Get(l.ctx, "captcha"+in.Account).Result()
	if result1 != in.Captcha {
		return nil, fmt.Errorf("图形验证码错误,登录失败")
	}

	var user models.User
	models.DB.Debug().Where("account = ?", in.Account).Find(&user)
	if user.ID == 0 {
		user = models.User{
			Account:   in.Account,
			Password:  pkg.Md5(in.Password),
			NickName:  fmt.Sprintf("用户_%d", rand.Intn(10000)),
			HeadImage: "https://ts1.tc.mm.bing.net/th/id/OIP-C.-rBqkricrrEXBZsFzjxtlQAAAA?w=206&h=211&c=8&rs=1&qlt=90&o=6&dpr=1.3&pid=3.1&rm=2",
		}
		models.DB.Debug().Create(&user)
	}

	if pkg.Md5(in.Password) != user.Password {
		return nil, fmt.Errorf("密码错误,登录失败")
	}

	return &shoprpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
